package belf.migrate.plugin.sqlserver.listener;

import belf.migrate.plugin.sqlserver.antlr.TSqlLexer;
import belf.migrate.plugin.sqlserver.antlr.TSqlParser;
import org.antlr.v4.gui.TreeViewer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import javax.swing.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class SqlServerTree {
    public static void main(String[] args) throws Exception {
        String sql = String.join("\n", Files.readAllLines(Paths.get(args[0])));
        long begin = System.currentTimeMillis();
        // 读取输入SQL语句

        // 创建一个CharStream
        CharStream input = CharStreams.fromString(sql);

        // 使用TSqlLexe进行词法分析
        TSqlLexer lexer = new TSqlLexer(input);

        // 使用CommonTokenStream将词法分析器生成的词汇流传递给解析器
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // 使用TSqlParser进行语法分析
        TSqlParser parser = new TSqlParser(tokens);

        // 从解析器中获取起始规则并进行解析
        ParseTree tree = parser.tsql_file();

        // 创建ParseTreeWalker
        ParseTreeWalker walker = new ParseTreeWalker();

        // 使用自定义Listener遍历解析树
        SqlServerCharacteristicListener listener = new SqlServerCharacteristicListener();
        walker.walk(listener, tree);
        System.out.println("==========" + listener.isRowCount());

        long end = System.currentTimeMillis();

        // 打印解析树
//        System.out.println(tree.toStringTree(parser));
//        System.out.println("spends: " + (end - begin));
//
//        // 使用TreeViewer展示解析树
//        JFrame frame = new JFrame("MySQL Parse Tree");
//        JPanel panel = new JPanel();
//        TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree);
//        viewer.setScale(1.5); // 缩放树的大小
//        panel.add(viewer);
//        frame.add(new JScrollPane(panel));
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        frame.setSize(800, 600);
//        frame.setVisible(true);
    }

}
